package cn.qingfeng.a003_chat_v2.server.handler;

import cn.qingfeng.a003_chat_v2.message.SendRequestMessage;
import cn.qingfeng.a003_chat_v2.server.session.Session;
import cn.qingfeng.a003_chat_v2.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class SendHandler extends SimpleChannelInboundHandler<SendRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SendRequestMessage msg) throws Exception {
        final Session session = SessionFactory.getSession();

        if (msg == null) {
            return;
        }

        String fromUsername = msg.getFromUsername();
        String toUsername = msg.getToUsername();
        String content = msg.getContent();
        Channel toChannel = session.getChannel(toUsername);
        toChannel.writeAndFlush(fromUsername + ":" + content);
    }
}